;;(load "sexp-aux.scm")
(def/err (sexp s n sls srs)
  (let ((str-l '())
	(st #f)
	(cyl-l '())
	(deli-str "")
	(ls 0)
	(rs 0)
	(res-str "")
	(res-cyl '())
	(res-st #f)
	)
    (if (not cyl-sexp-flag)
	(set! cyl-sexp-flag #t))
    (push "(" str-l)
    (push (list "(" 1 s-exp-begin-coding 'lisp-begin (cyl-serial)) cyl-l)
    (tr-string (i c s n)
	       ;;(y-or-n "sexp:sls=~a,srs=~a,cyl-l=~a,i=~a.\n" sls srs cyl-l i)
	       (cond
		;;rule: only pure yexp can be in sexp,not permit macro and keyword clause.Another way,not 分隔符 in sexp,only deli in sexp.
		((rd-deli c)
		 (let-set! (deli-str i) (run/err rd-skip-deli s i))
		 (push (list deli-str (string-length deli-str) deli-std-coding '分隔符 (cyl-serial)) cyl-l)
		 (push deli-str str-l)
		 )
		((rd-s-beg c)
		 (set! sls (+ sls 1))
		 (let-set! (res-str i sls srs res-cyl res-st)(run/err sexp s (+ i 1) sls srs))
		 (push res-cyl cyl-l)
		 (push res-str str-l)
		 )
		((rd-s-end c)
		 ;;(y-or-n "sexp1:sls=~a,srs=~a,cyl-l=~a,i=~a.\n" sls srs cyl-l i)
		 (set! srs (+ srs 1))
		 (if (>= sls srs)
		     (begin
		       (push (list ")" 1 s-exp-end-coding 'lisp-end (cyl-serial)) cyl-l)
		       (push ")" str-l)
		       ;;(y-or-n "sexp2:sls=~a,srs=~a,cyl-l=~a,i=~a.\n" sls srs cyl-l i)
		       ;;(y-or-n "merge-str:~a\n" (merge-str i str-l))
		       ;;(y-or-n "merge-cyl:~a\n" (merge-cyl i cyl-l 'lisp-call))
		       (exit-sexp (list (merge-str i str-l) i sls srs (merge-cyl i cyl-l 'lisp-call) 'lisp-call)))
		     (exit-sexp (list 'err i 1 '非法语法 (err-format 'sexp i "lisp表达式中左括号数[~a]小于右括号数[~a]。" sls srs)))))
		(else
		 (let-set! (res-str i ls rs res-cyl res-st) (run/err yexp s i 0 0))
		 ;;rule:sexp only check the first parameter if lisp-func, and the number of the lisp function parameter.
		 ;;the lisp-func must at system dict.new lisp-func be added in system dict by yourself.
		 ;;we'll add the function to import lisp-func to system dict.
		 ;;(y-or-n "sexp:guide=~a,res-cyl=~a.\n" cyl-sexp-guide res-cyl)
		 (set! res-cyl (run/err rewrite-lisp-func/aux res-cyl))
		 ;;(y-or-n "sexp:res-cyl=~a.\n" res-cyl)
		 (push res-cyl cyl-l)
		 (push res-str str-l)
		 )
		))
    (let ((i (string-length s)))
      ;;(y-or-n "sexp:sls=~a,srs=~a,cyl-l=~a.\n" sls srs cyl-l)
      (if (= sls srs)
	  (list 'err i 1 '非法语法 (err-format 'sexp i "开发错误，左右括号相等应该已经返回。"))
	  (list 'err i 1 '非法语法 (err-format 'sexp i "输入错误，左括号[~a]与右括号[~a]不相等。"  sls srs))
	  ))
    ))
	    
(define (rd-skip-deli s n)
  (call/cc (lambda (exit-rd-skip-deli)
	     (let ((deli-str ""))
	       (tr-string (i c s n)
			  (if (rd-deli c)
			      (set! deli-str (string-append deli-str (string c)))
			      (exit-rd-skip-deli (list deli-str (- i 1)))))
	       (list deli-str (string-length s))))))

		 
		 
    
